from django.http import Http404, HttpResponseServerError, \
	HttpResponse
from django.shortcuts import render_to_response
from nmj.sqlite.nmj_db import NMJ_SERIE_TYPE
from nmj.sqlite.tables import Show, Video, VideoSynopsis
from nmj.tools.helpers import download_image
from pywebnmj.urls import STATIC_ROOT
from pywebnmj.views import __get_library
import os
import shutil

def __get_directory(session, directory_id):
	return session.get("nmj_dirs", [])[int(directory_id)]

def __get_shows(directories, **kwargs):
	shows = []
	for rank, directory_dict in enumerate(directories):
		directory = directory_dict["directory"]
		type = directory_dict["type"]
		library = __get_library(directory, type)
		tmp_shows = library.get_all(Show, **kwargs)

		for show in tmp_shows:
			show.directory_index = rank
			show.original_directory = directory
			show.original_type = type
			if show.detail_poster:
				src = os.path.join(directory, show.detail_poster)
				dest = os.path.join(STATIC_ROOT, "movies", "posters", os.path.basename(show.detail_poster))
				show.poster = os.path.basename(show.detail_poster)
				if os.path.exists(src):
					if not os.path.exists(dest):
						shutil.copyfile(src, dest)
				else:
					show.poster = "unknown.png"
			else:
				show.poster = "unknown.png"

			if show.wallpaper:
				src = os.path.join(directory, show.wallpaper)
				dest = os.path.join(STATIC_ROOT, "movies", "posters", os.path.basename(show.wallpaper))
				show.background = os.path.basename(show.wallpaper)
				if not os.path.exists(dest):
					shutil.copyfile(src, dest)

			synopsises = library.get_all(VideoSynopsis, show_id=show.show_id)
			if synopsises:
				show.synopsis = synopsises[0].content
		shows.extend(tmp_shows)

	shows.sort(key=lambda x : x.title)
	return shows

def __load_episodes(show):
	library = __get_library(show.original_directory, show.original_type)
	episodes = library.get_all(Video, show_id=show.show_id)
	episodes.sort(key=lambda x:"%s%s" % (x.season or 0, x.episode or 0))
	return episodes

def __is_watched(show):
	library = __get_library(show.original_directory, show.original_type)
	videos = library.get_all(Video, show_id=show.show_id)
	return 0 not in [video.play_count for video in videos]

def edit(request, directory_id, movie_id):
	directory = __get_directory(request.session, directory_id)
	library = __get_library(directory["directory"], directory["type"])
	show = __get_shows([directory, ], show_id=movie_id)[0]
	title = request.POST.get('title', show.search_title)
	real_title = title
	if show.show_type == NMJ_SERIE_TYPE:
		real_title += "_-_0_"

	propositions = library.search(real_title)
	for proposition in propositions:
		if not proposition.posters:
			proposition.posters = [{"url" : "/static/movies/posters/unknown.png" }]
		else:
			poster = proposition.posters[0].url
			destination = os.path.join(STATIC_ROOT, "tmp", os.path.basename(poster))
			download_image(poster, destination)
			proposition.posters = [{"url" : "/static/tmp/%s" % os.path.basename(poster)}]
	return render_to_response("movies/choose.html",
		{"propositions": propositions, "title":title, "request_path" : request.path}
	)

def view_all(request):
	return render_to_response("movies/index.html", {"all_movies": __get_shows(request.session.get("nmj_dirs", {}))})

def view_movie(request, directory_id, movie_id):
	movie_id = int(movie_id)
	matching_shows = __get_shows([__get_directory(request.session, directory_id), ], show_id=movie_id)
	if len(matching_shows) == 0:
		return Http404
	if len(matching_shows) > 1:
		return HttpResponseServerError("Many movies match the movie id : %s" % movie_id)
	show = matching_shows[0]
	if show.show_type == NMJ_SERIE_TYPE:
		show.episodes = __load_episodes(show)
		show.watched = (0 not in [episode.play_count for episode in show.episodes])
	else:
		show.watched = __is_watched(show)

	return render_to_response("movies/movie.html", {"movie": show})


def video_watched_toggle(request, directory_id, movie_id):
	directory = __get_directory(request.session, directory_id)
	library = __get_library(directory["directory"], directory["type"])
	video = library.get_all(Video, video_id=movie_id)[0]
	library.update_item(video, play_count=int(not video.play_count))
	return HttpResponse(video.play_count)

def show_watched_toggle(request, directory_id, movie_id):
	directory = __get_directory(request.session, directory_id)
	watched = __is_watched(__get_shows([__get_directory(request.session, directory_id), ], show_id=movie_id)[0])
	library = __get_library(directory["directory"], directory["type"])
	videos = library.get_all(Video, show_id=movie_id)
	for video in videos:
		library.update_item(video, play_count=int(not watched))
	return HttpResponse(int(not watched))
